﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Configuration;
using Jobping.Database;
using System.IO;

namespace Jobping.ShortUrls
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : System.Web.HttpApplication
    {
        public static readonly string ConnectionString;

        static MvcApplication()
        {
            ConnectionString = ConfigurationManager.ConnectionStrings["DbConnectionString"].ConnectionString;
        }

        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.IgnoreRoute("favicon.ico");

            routes.MapRoute(
                "Default", // Route name
                "", // URL with parameters
                new { controller = "Home", action = "Index" } // Parameter defaults
            );


            routes.MapRoute(
               "Redirect", // Route name
               "{shortUrl}", // URL with parameters
               new { controller = "Home", action = "Follow" } // Parameter defaults
           );
        }

        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            RegisterRoutes(RouteTable.Routes);

            ConfigureDatabase();
        }

        private void ConfigureDatabase()
        {
            EnsureSqlExpress();

            // Run db migrations.
            var migrator = new MigrationHelper(DatabaseProvider.SqlServer, MvcApplication.ConnectionString);
            migrator.MigrateTo(0);
            migrator.MigrateToLatest();
        }

        private void EnsureSqlExpress()
        {
            //if we are using sqlExpress, copy the blank db if needed.
            string DataDirectoryTag = "|DataDirectory|\\";
            if(!ConnectionString.Contains(DataDirectoryTag))
                return;

            int startIndex = ConnectionString.IndexOf(DataDirectoryTag) + DataDirectoryTag.Length;
            int endIndex = ConnectionString.IndexOf(";", startIndex);

            string appData = Server.MapPath("~/App_Data");
            string targetDbName = ConnectionString.Substring(startIndex,  endIndex - startIndex);
            string targetFilename = Path.Combine(appData, targetDbName);
            
            string targetLogFilename = Path.GetFileNameWithoutExtension(targetFilename) + "_log.ldf";
            targetLogFilename = Path.Combine(appData, targetLogFilename);

            string blankFilename = Path.Combine(appData, "Blank.mdf");
            string blank_LogFilename = Path.Combine(appData, "Blank_log.ldf");

            //Already have a db.
            if(File.Exists(targetFilename))
                return;

            if(!File.Exists(blankFilename))
                throw new ApplicationException("Your database could not be found, please create a new SqlExpress database called \"" + targetFilename + "\" and/or update your connection string. PS: if there is a blank db called blank.mdf in your app_data directory, we would have used that.");

            //Copy the blank to the target
            File.Copy(blankFilename, targetFilename);

            //Copy the blank log file
            File.Copy(blank_LogFilename, targetLogFilename);

        }
    }
}